#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <libgen.h>

#include <glib.h>
#include <gtk/gtk.h>
#include <glade/glade.h>
#include <libintl.h>

#include "totem-plugin.h"
#include "lrcshow.h"
#include "totem.h"
#include "lmp-debug.h"
#include "lmp-lyric-download.h"
#include "totem-lrc.h"

#define _(a) gettext(a)

//static     GtkWidget *win = NULL;
static     GtkWidget *view;
//static     GtkWidget *scroll;
static lrc_st lrc_line[max_lrc_line];
static gchar *lines[max_lrc_line];

gint64 read_time_at_line(gchar *line);
static void set_a_to_b(gchar *str,char a,char b);
static char *get_addr_last(char *str,char ch);
static void fuck_lrc_line(void);
static gboolean load_lrc_into_mem(gchar *lrc);

void status_hide_show(GtkStatusIcon *status_icon,GtkWidget *data);
void status_pop_menu(GtkStatusIcon* icon, guint button, guint activate_time,gpointer user_data);
void on_setting(GtkMenuItem *menuitem,gpointer data);
void on_totem(GtkMenuItem *menuitem,GtkWindow *data);
void on_quit(GtkMenuItem *menuitem,gpointer data);
static gboolean lrc_button_release(GtkWidget* treeview,
                               GdkEventButton* event,
                               gpointer userdata);
static void on_search_item(GtkMenuItem *menuitem,gpointer data);
static void on_reload_item(GtkMenuItem *menuitem,gpointer data);
static void on_about_item(GtkMenuItem *menuitem,gpointer data);
gpointer lrc_reload_thread(gpointer data);
void fork_lrc_show_thread(void);
//extern gchar *lrc_plugin_get_artist_title(gboolean bl);
//static GMutex* lock = NULL;
//gint64 now = 0;

gchar *get_addr(gchar *str,char ch)
{
	char *tmp=str;
	while(*tmp){
		if(*tmp==ch)
			return ++tmp;
		tmp++;
	}
	return *tmp?str:NULL;
}

void set_a_to_b(gchar *str,char a,char b)
{
  while(*str){
    if(*str==a)
       *str=b;
    str++;
  }
}

void fuck_lrc_line(void)
{
  int i=0;
  FILE *f=fopen("/tmp/log.f","w");
  while(lrc_line[i].tm>-1){
    fprintf(f,"pt=%d:tm=%lld\n",lrc_line[i].pt,lrc_line[i].tm);
    i++;
  }
  fclose(f);
}

char *get_addr_last(char *str,char ch)
{
  int i=0,len,j=0;
  len=strlen(str);
  while(str[i]){
    if(str[i++]==ch)
          j=i;
  }
  return str+j;
}

void sort_lines(void)
{
  lrc_st tmp={0,0};
  gint i=0,j=0;
  tmp=lrc_line[i];
  while(lrc_line[i].tm>-1){
    j=i+1;
    while(lrc_line[j].tm>-1){
      if(lrc_line[i].tm>lrc_line[j].tm){
         tmp=lrc_line[i];
         lrc_line[i]=lrc_line[j];
         lrc_line[j]=tmp;
      }
      j++;
    }
  i++;
  }
}

#define max_reads 2048
gboolean filecopy(const char *src,const char *dest)
{
	FILE *f1;
	FILE *f2;
	char line[max_reads] = {0};

	size_t n = 0;

	f1= fopen(src,"r");
	if(f1){
		f2 = fopen(dest,"w");
	}else{
		lmp_debug(strerror(errno));
		return FALSE;
	}
	if(!f2){
		lmp_debug("fopen():%s:%s.",dest,strerror(errno));
		return FALSE;
	}
	while(!feof(f1)){
		n = fread(line,1,max_reads,f1);
		fwrite(line,1,n,f2);
//		print_log("%s add %s",dest,line);
	}

	fclose(f1);
	fclose(f2);

	return TRUE;

}


GtkWidget* load_lrc_ui(gchar *ui)
{
      GtkWidget *scroll;
//    GladeXML *xml = NULL;
//    if(GTK_IS_WINDOW(win))
//         return win;
/*    if(ui&&access(ui,F_OK)==0){
       xml = glade_xml_new(ui, NULL, NULL);
     }else {
       fprintf(stderr,"Access():%s .\n",strerror(errno));
       return NULL;
	  }
	  
    win = glade_xml_get_widget(xml,"window1");
    view = glade_xml_get_widget(xml,"textview1");
    scroll = glade_xml_get_widget(xml,"scrolledwindow1");
*/
    view = gtk_text_view_new ();
    gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(view),FALSE);
    gtk_text_view_set_justification(GTK_TEXT_VIEW(view),GTK_JUSTIFY_CENTER);
    gtk_text_view_set_pixels_above_lines(GTK_TEXT_VIEW(view),2);
    gtk_text_view_set_pixels_below_lines(GTK_TEXT_VIEW(view),2);
    gtk_text_view_set_pixels_inside_wrap(GTK_TEXT_VIEW(view),2);
//    gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(view),GTK_WRAP_WORD);
    gtk_container_set_resize_mode(GTK_CONTAINER(view), GTK_RESIZE_PARENT);

    buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (view));
    scroll = gtk_scrolled_window_new (NULL, NULL);
    gtk_container_set_resize_mode(GTK_CONTAINER(scroll),GTK_RESIZE_PARENT);
    gtk_scrolled_window_set_shadow_type(
                                        GTK_SCROLLED_WINDOW (scroll),
                                        GTK_SHADOW_OUT);
    gtk_scrolled_window_set_policy (
                   GTK_SCROLLED_WINDOW (scroll),
                   GTK_POLICY_NEVER/*GTK_POLICY_AUTOMATIC*/,
                   GTK_POLICY_AUTOMATIC);

    gtk_container_add (GTK_CONTAINER (scroll), view);
    gtk_widget_show_all(scroll);
//    gtk_window_set_title (GTK_WINDOW(win),"歌词秀");

		tag = gtk_text_buffer_create_tag (buffer,
		                                 "blue_foreground",
		                                 "foreground",
		                                 "blue",
		                                  NULL);
		gtk_text_buffer_set_text (buffer,
		                          "\n\n\n\n        歌词秀，让我秀歌词!         \n",
		                         -1);
/*	  
		g_signal_connect(GTK_OBJECT(win),
		                "delete_event",
		                GTK_SIGNAL_FUNC(hand_win),
		                NULL);
*/
		g_signal_connect(GTK_WIDGET(view),
		                "button-release-event",
		                GTK_SIGNAL_FUNC(lrc_button_release),
		                NULL);

		g_signal_connect(GTK_WIDGET(view),
		                "button-press-event",
		                GTK_SIGNAL_FUNC(lrc_button_release),
		                NULL);

	return scroll;
}

static gboolean lrc_button_release(GtkWidget* treeview,
                               GdkEventButton* event,
                               gpointer userdata)
{
//	  lmp_debug("");
    if (event->type == GDK_BUTTON_RELEASE  &&  event->button == 3)
    {
      lmp_debug("right.");
      static GtkWidget *menu = NULL;
      GtkWidget *search;
      GtkWidget *reload;
      GtkWidget *about;
      GtkWidget *sep;
      
      if(!menu){
        menu = gtk_menu_new();
        search = gtk_menu_item_new_with_mnemonic(_("歌词搜索(_S)"));
        reload = gtk_menu_item_new_with_mnemonic(_("重新加载(_R)"));
        about = gtk_menu_item_new_with_mnemonic(_("关于歌词秀(_A)"));
        sep = gtk_separator_menu_item_new();

        gtk_menu_shell_append(GTK_MENU_SHELL(menu),search);
        gtk_menu_shell_append(GTK_MENU_SHELL(menu),reload);
        gtk_menu_shell_append(GTK_MENU_SHELL(menu), sep);
        gtk_menu_shell_append(GTK_MENU_SHELL(menu),about);

        g_signal_connect(GTK_WIDGET(search),"activate",G_CALLBACK(on_search_item),NULL);
        g_signal_connect(GTK_WIDGET(reload),"activate",G_CALLBACK(on_reload_item),NULL);
        g_signal_connect(GTK_WIDGET(about),"activate",G_CALLBACK(on_about_item),NULL);

        }
        gtk_widget_show_all(GTK_WIDGET(menu));
        gtk_menu_popup(GTK_MENU(menu),
                   NULL,
                   NULL,
                   NULL,
                   NULL, 1,
                   gtk_get_current_event_time());
    }
    return TRUE;
}

static void on_reload_item(GtkMenuItem *menuitem,gpointer data)
{

   lmp_debug("reload");
   lrc_set_view("\n\n\n\n\n加载中.....");
   is_down_ok = TRUE;
   is_lrc_in_buff = FALSE;
   if(set_and_get_timeout(0)==0)
        kill(getpid(),sig_reload_lrc);
}

static void on_search_item(GtkMenuItem *menuitem,gpointer data)
{
  gtk_widget_show_all(
   lrc_selection_dialog(NULL)
  );

  lmp_debug("");
  gtk_list_store_clear(
                     GTK_LIST_STORE(
                     gtk_tree_view_get_model(
                        GTK_TREE_VIEW(get_store_pointer(NULL))
                     )));
  gchar *text = lrc_plugin_get_artist_title(TRUE);
  gtk_entry_set_text(GTK_ENTRY(lrc_text.artist),text);
  g_free(text);

  text = lrc_plugin_get_artist_title(FALSE);
  gtk_entry_set_text(GTK_ENTRY(lrc_text.title),text);
  g_free(text);
}

static void on_about_item(GtkMenuItem *menuitem,gpointer data)
{
	gchar *authors[]={
	"wkt <wkt55555@163.com>",
	NULL,
	};
	gchar *copyright = "Copyright © 2008 wkt";
	gchar *description = "扩展Totem的功能使其可以显示、搜索和下载歌词的插件";
	gtk_show_about_dialog (NULL,//GTK_WINDOW (win),
	                      "program-name","LrcShow",
	                      "version",LRC_VERSION,
	                      "copyright",copyright,
	                      "comments",description,
	                      "authors",authors,
	                      "logo-icon-name","gtk-about",
	                      "website-label","欢迎访问项目主页\n错误报告:wkt55555@163.com",
	                      "website","http://tlrcshow.googlecode.com/",
	                      NULL);

}

void lrc_set_view(gchar *text)
{
  is_lrc_in_buff = FALSE;
/*  GtkTextIter start;
  lmp_debug("set text");
  gtk_text_buffer_get_start_iter(buffer,&start);
  gtk_text_view_scroll_to_iter(GTK_TEXT_VIEW(view),
                              &start,
                              0.1,
                              TRUE,
                              0.3,
                              0.4);
  gtk_text_buffer_set_text(buffer,text,-1);
*/  lmp_debug("text seted");
}

void clear_view(void)
{
 lmp_debug("clear buffer");
 is_lrc_in_buff = FALSE;
 gtk_text_buffer_set_text(buffer,"",-1);
 lmp_debug("buffer cleaned");
}

void load_lrc_file(gchar *file,gchar *arts,gchar *title)
{
    static _THREAD_DATA da = {0};
    lmp_debug("");

    char *lyricfile = lrc_get_lrc_fullpath();
    if(access(lyricfile,F_OK)==0){
        is_down_ok = TRUE;
        if(set_and_get_timeout(0)==0)
            kill(getpid(),sig_reload_lrc);
        g_free(arts);
        g_free(title);
    }else{
        lmp_debug("artist:%s title: %s.",arts,title);
        da.artist = arts;
        da.title = title;

        da.treeview = GTK_WIDGET(get_store_pointer(NULL));

        gtk_list_store_clear(
                     GTK_LIST_STORE(
                     gtk_tree_view_get_model(
                            GTK_TREE_VIEW(da.treeview)
                     )));

       lrc_set_view("\n\n\n\n歌词搜索中......");

       gchar *text = lrc_plugin_get_artist_title(TRUE);
       gtk_entry_set_text(GTK_ENTRY(lrc_text.artist),text);
       g_free(text);

       text = lrc_plugin_get_artist_title(FALSE);
       gtk_entry_set_text(GTK_ENTRY(lrc_text.title),text);
       g_free(text);

       GError *error = NULL;
       da.id=0;
       if(!g_thread_create((GThreadFunc)g_thread_on_search,&da,FALSE,&error)){
            fprintf(stderr,
                    "Failed to create g_three_on_search thread: %s\n",
                    error->message);
           g_error_free(error);
        }
    }
    lmp_debug(lyricfile);
    g_free(lyricfile);

}

void sig_handler_reload(int sig)
{
      lmp_debug("Signal coming.");
      if(!(totem_is_playing(lrc_totem)||totem_is_paused(lrc_totem))){
        lmp_debug("I do nothing .");
        return;
      }
      char *lyric_file = lrc_get_lrc_fullpath();
      if(is_down_ok&&lrc_insert_buffer(lyric_file)){
          is_lrc_in_buff = TRUE;
      }else{
          is_lrc_in_buff = FALSE;
          lrc_set_view("\n\n\n\n\n歌词加载失败!!!");
      }
      g_free(lyric_file);
      if(is_lrc_in_buff){
          set_and_get_timeout(1);
          fprintf(stderr,"***Start a NEW timeout.***\n");
          g_timeout_add(lrc_tm,play_lrc,lrc_totem);
       }
     lmp_debug("signal done");
}

gint64 read_time_at_line(gchar *line)
{
	gint64 t=0;
	gchar *str = line;

	if(str[1]>'9'&&str[1]<'0')
	   return 0;

	str++;

	t = atoll(str)*60*1000;
	t = t+atof(get_addr(str,':'))*1000;

	return t<0?-t:t;///我不知道时间为负值的意义。

}

gboolean load_lrc_into_mem(gchar *lrc)
{
  FILE *f;
  size_t len = 0,i=0,j=0;
  char *line= NULL;
  char *tmp = NULL;

  lmp_debug("try to load %s",lrc);
  f=fopen(lrc,"r");
  if(!f){
    fprintf(stderr,"fopen():%s:%s.\n",lrc,strerror(errno));
    return FALSE;
  }

  lrc_line[j].pt = i;
  lrc_line[j++].tm = 0;
  lrc_line[j].tm = -1;
  lines[i++] = g_strdup("");

  while(getline(&line,&len,f)!=-1&&j<max_lrc_line){
     if(*line!='[')continue;
     char *head = tmp = all_to_utf8(line+1,-1);
     set_a_to_b(tmp,'\n',0);//拿掉换行符,有的换行符在textview上是两个的效果。
     set_a_to_b(tmp,'\r',0);//在这里去掉行符有点不好
     if(*tmp<'0'||*tmp>'9'){//处理没有时间的行
        lines[i] = g_strdup(get_addr(tmp,':'));//仅显示：后的文字.
        lrc_line[j].tm = 0;
        lrc_line[j++].pt = i;
        set_a_to_b(lines[i++],']',' ');
        lrc_line[j].tm=-1;
        goto ex;
     }

     do{///处理多个时间在同一行
        lrc_line[j].tm = read_time_at_line(tmp);
        lrc_line[j++].pt=i;
        lrc_line[j].tm=-1;
//        g_print("tm =%lld tmp = %s\n",lrc_line[j-1].tm,tmp);
        tmp = get_addr(tmp,'[');
     }while(tmp&&j<max_lrc_line);

     lines[i++] = g_strdup(get_addr_last(head,']'));
     ex: g_free(head);
//    g_print("i=%d,%s\n",i-1,lines[i-1]);
 }

  if(line)
     free(line);
  fclose(f);
// lmp_debug("%s",tmp);
 return i>2; ///如果文件合法，应该不会i>2.
}

gboolean lrc_insert_buffer(gchar *file/*,gchar *arts,gchar *title*/)
{
	gsize j=0;
	GtkTextIter old;

	lmp_debug("%s",file);
	if(!load_lrc_into_mem(file)){
		return FALSE;
	}

	sort_lines();//根据时间给指向各个字串的索引排序
	clear_view();//清空textveiw
//	  gtk_widget_set_size_request(view,40,80);
	gtk_text_buffer_get_iter_at_offset (buffer, &old, 0);

	while(lrc_line[j].tm>-1){
		gchar *lrcstr = lines[lrc_line[j].pt];

		gtk_text_buffer_insert (buffer, &old,lrcstr,-1);
		gtk_text_buffer_insert (buffer, &old,"\n",-1);//所有的行都没有换行符，所以都需要加上。
		
		j++;
	}

	gtk_text_buffer_insert (buffer, &old,"\n\n\n",-1);
	j=0;

	while(lrc_line[j].tm>-1){
		g_free(lines[lrc_line[j].pt]);
		lines[lrc_line[j++].pt]=NULL;
	}
	lmp_debug("");
//	fuck_lrc_line();
//	is_lrc_in_buff = TRUE;
	return TRUE;
}

gint set_and_get_timeout(gint c)
{
	static gint count = 0;
	if(c==-1) count--;
	if(c== 1) count++;
	if(count<0) count = 0;
	return count;
}

gboolean play_lrc(gpointer data)
{
	gint64 t=0;
	Totem *totem = (Totem *)data;
	if(is_lrc_in_buff){
		t = totem_get_current_time(totem);
		show_diff_in_lrc(t);
	}else{
		g_print("timeout exit:%lld.\n",totem_get_current_time(totem));
		lmp_debug("**Stop old timeout**");
		set_and_get_timeout(-1);
		if(is_down_ok){
			kill(getpid(),sig_reload_lrc);
		}
		return FALSE;
	}
	return TRUE;
}

gint show_diff_in_lrc(gint64 tm)
{
//lmp_debug("tm=%lld",tm);
	GtkTextIter start, end;
	gint index=0;
	static gint64 oldtm = 0;
	gint64 tm1,tm2;
	if(oldtm==tm)
		return index;
	oldtm = tm;
	tm1 = lrc_line[index].tm;
	while(tm1>-1&&is_lrc_in_buff){
		tm2 = lrc_line[index+1].tm;
		if(tm1&&(tm2>=tm||tm2<0)&&tm>=tm1){ //
			gdk_threads_enter();
			gtk_text_buffer_get_start_iter(buffer,&start);
			gtk_text_buffer_get_end_iter (buffer,&end);
			gtk_text_buffer_remove_all_tags(buffer,&start,&end);
			gtk_text_buffer_get_iter_at_line(buffer,&start,index);
			gtk_text_buffer_get_iter_at_line(buffer,&end,index+1);
			gtk_text_buffer_apply_tag (buffer, tag, &start, &end);

			if(index%3==2)
				gtk_text_view_scroll_to_iter(GTK_TEXT_VIEW(view),&start,0.1,TRUE,0.3,0.4);
//			g_print("index=%d--%lld:%lld\n",index,tm,lrc_line[index].tm);
			gdk_flush();
			gdk_threads_leave();
			return index;
		}
		index++;
		tm1 = lrc_line[index].tm;
	}
	return index;
}

gboolean append_new_string_to_conffile(char *key,char *string)
{
	FILE *pin = NULL;
	FILE *pout = NULL;
	char *conf = g_strdup_printf("%s/.lrcconf",g_get_home_dir());
	char *tmpfile = "/tmp/.Iamlrcshowtmp__";
	gboolean find = FALSE;
	size_t len = 0;
	char *line = NULL;
	if(g_file_test(conf,G_FILE_TEST_EXISTS))
		pin = fopen(conf,"r");
	if(pin)
		pout = fopen(tmpfile,"w");
	else
		return FALSE;
	if(!pout){
		if(pin)
			fclose(pin);
		lmp_debug(strerror(errno));
		return FALSE;
	}
	lmp_debug("key=%s",key);
	while(pin&&getline(&line,&len,pin)!=-1){
		lmp_debug(line);
		if(g_strrstr (line,key)){
			fprintf(pout,"%s=%s\n",key,string);
			find = TRUE;
		}else{
			fprintf(pout,"%s",line);
		}
	}
	if(line)
		free(line);
	if(pin)
		fclose(pin);
	if(!find){
		lmp_debug(string);
		fprintf(pout,"%s=%s\n",key,string);
	}
	fclose(pout);
	if(rename(tmpfile,conf)==0){
		find = TRUE;
	}else{
		lmp_debug("rename(%s,%s):%s",tmpfile,conf,strerror(errno));
		find = filecopy(tmpfile,conf);
	}
	g_free(conf);

	return find;
}

void lrc_set_lyric_dir(char *dir)
{
	gchar *lrcdir = NULL;
	lrcdir = dir&&*dir?dir:(char *)g_get_home_dir();
	append_new_string_to_conffile("lrcdir",lrcdir);
}

char *lrc_get_lyric_dir(void)
{
	static char line[1024];
	char *value = NULL;
	value = lrc_get_value("lrcdir");
	if(!value){
		char *tmp = g_strdup_printf("%s/Lyrics",g_get_home_dir());
		g_strlcpy(line,tmp,1024);
		g_free(tmp);
	}else{
		g_strlcpy(line,value,1024);
		g_free(value);
	}
	if(!g_file_test(line,G_FILE_TEST_IS_DIR))
		mkdir(line,0777);
	return line;
}

gchar *lrc_get_lrc_fullpath(void)
{
	char *lrcname = lrc_plugin_get_lrcname();
	char *fullpath = g_strdup_printf("%s/%s",lrc_get_lyric_dir(),lrcname);
	g_free(lrcname);
	return fullpath;
}

gchar* lrc_get_value(gchar *name)
{
   size_t len = 0;
   char *line = NULL;
   char *t = NULL;
   FILE *f;
   if(!(name&&*name))
      return t;
   char *conf = g_strdup_printf("%s/.lrcconf",g_get_home_dir());
   const char *mod="r";
   if(!g_file_test(conf,G_FILE_TEST_EXISTS)){
      mod = "w+";
   }
   f = fopen(conf,mod);
   g_free(conf);
   if(!f)
     return t;
   while(getline(&line,&len,f)!=-1){
      if(g_strrstr(line,name)){
         t = g_strdup(get_addr(line,'='));
         len = strlen(t)-1;
        if(t[len]=='\n'||t[len]=='\r')
           t[len]=0;
         break;
      }
   }

   if(line)
      free(line);
   fclose(f);
   return t;
}



GtkStatusIcon *status_icon(GtkWidget *widget,gchar *ico)
{
   GtkStatusIcon* icon;
 
   if(ico&&access(ico,F_OK)==0)
      icon = gtk_status_icon_new_from_file (ico);
   else 
      icon = gtk_status_icon_new_from_stock (GTK_STOCK_YES);
   gtk_status_icon_set_tooltip(icon,_("Show lyric window "));
   g_signal_connect((gpointer)icon, "activate", G_CALLBACK(status_hide_show), widget);
//   g_signal_connect((gpointer)icon, "popup-menu", G_CALLBACK(status_pop_menu), menu);

  return icon;
}

void status_hide_show(GtkStatusIcon *status_icon,GtkWidget *data)
{

//  if( GTK_IS_WIDGET(data)&&!GTK_WIDGET_VISIBLE (data)){
     gtk_window_present(GTK_WINDOW(data));
//  }
  g_object_unref(status_icon);
}
/*
void status_pop_menu(GtkStatusIcon* icon,
                     guint button,
                     guint activate_time,
                     gpointer user_data)
{

    gtk_widget_show(GTK_WIDGET(user_data));
    gtk_menu_popup(GTK_MENU(user_data),
                   NULL,
                   NULL,
                   NULL,
                   NULL, 1,
                   gtk_get_current_event_time());
}

GtkWidget *status_menu(GtkWindow *data)
{

    GtkWidget* set ;
    GtkWidget* totem ;
    GtkWidget* menu ;
    
    menu = gtk_menu_new();
    
    set = gtk_menu_item_new_with_mnemonic(_("_Setting"));
    totem = gtk_menu_item_new_with_mnemonic(_("_Totem"));
    gtk_menu_shell_append(GTK_MENU_SHELL(menu),set);
    gtk_menu_shell_append(GTK_MENU_SHELL(menu),totem);

    GtkWidget* sep = gtk_separator_menu_item_new();
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), sep);

    GtkWidget* quit = gtk_menu_item_new_with_mnemonic(_("_Quit"));
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), quit);

    gtk_widget_show(set);
    gtk_widget_show(totem);
    gtk_widget_show(sep);
    gtk_widget_show(quit);

    g_signal_connect((gpointer)set, "activate", G_CALLBACK(on_setting),NULL);
    g_signal_connect((gpointer)totem, "activate", G_CALLBACK(on_totem),data);
    g_signal_connect((gpointer)quit, "activate", G_CALLBACK(on_quit), NULL);
//    g_signal_connect((gpointer)quit, "activate", G_CALLBACK(gtk_widget_show),menu);
   return menu;
}

void on_setting(GtkMenuItem *menuitem,gpointer data)
{
  lmp_debug("");
//  lmp_debug_set_flag(FALSE);//不显示debug信息
}

void on_totem(GtkMenuItem *menuitem,GtkWindow *data)
{
  lmp_debug("");
  static gint f=1;

  if(!f&&!gtk_window_is_active (GTK_WINDOW(data))){
     lmp_debug("present");
     gtk_window_present(GTK_WINDOW(data));
     f=1;
  }else{
     lmp_debug("hide");
     gtk_widget_hide(GTK_WIDGET(data));
     f=0;
   }
}

void on_quit(GtkMenuItem *menuitem,gpointer data)
{
  lmp_debug("");
  gtk_widget_hide(win);
  g_signal_emit_by_name(
          totem_get_main_window(lrc_totem),
          "delete-event");
}

gboolean lrc_get_totem_flag(void)
{
 return TRUE;
}
*/

void on_destroy(GtkObject *object,
               gpointer   user_data)
{
	g_object_unref(user_data);
	lmp_debug("destroy.");
}

gboolean on_lrcshow_win(GtkWidget *widget,GdkEvent  *event,gpointer data)
{
  lmp_debug("");
  GtkStatusIcon *s_icon = status_icon(widget,NULL);
  g_signal_connect(widget,"destroy",G_CALLBACK(on_destroy),s_icon);
  gtk_widget_hide(widget);
  return TRUE;
}

gchar *all_to_utf8(gchar *str,gsize max)
{
   gchar *code[]={
   "GB18030", "GB2312","GBK","CP936",
   "CN-GB","GB13000","utf16","CN-BIG5","BIG-5",NULL
   };          ////如果还有什么其它可能的就全加进来。我就不信了还能有乱码？
// lmp_debug("");
   gchar *new = NULL;
   gsize i=0,r=0,w=0;
   if(g_utf8_validate (str,max,NULL))
      return g_strdup(str);///没办法为了统一处理
   while(code[i]){	//我觉得这个循环花不了多少时间。

      new = g_convert(str,-1,"utf-8",code[i],&r,&w,NULL);
      if(new){
          if(g_utf8_validate (new,w,NULL))
          return new;
      }else
         g_free(new);
         i++;
   }
   lmp_debug("NULL");
   return NULL;
}


gboolean hand_win(gpointer data)
{
  gtk_widget_hide(GTK_WIDGET(data));
  lrc_show = FALSE;
  return TRUE;
}

gchar *encode_to_self(gchar *str)
{
	GError* error = NULL;
	if(!str)return NULL;
	gchar* pgb = g_convert(str, -1, "iso-8859-1", "utf-8", NULL, NULL, &error);
//	lmp_debug("pgb:%s",pgb?all_to_utf8(pgb,-1):pgb);
	if(error)
	{
		lmp_debug("g_convert: %s", error->message);
//		lmp_debug("%s",str);
		return g_strdup(str);
	}
	return pgb;
}

GtkWindow *lrc_show_lrc_in_win(GtkWidget *wd)
{
	lmp_debug("go");
	GtkWidget *win = gtk_window_new (GTK_WINDOW_TOPLEVEL);

	gtk_widget_set_size_request(win,-1,450);
//	lmp_debug("test before title");
	char *ti = lrc_plugin_get_artist_title(FALSE);
	lmp_debug(ti);
	if(ti&&*ti){
		gtk_window_set_title(GTK_WINDOW(win),ti);
	}
	if(ti)
		g_free(ti);

//	gtk_widget_set_parent(win,GTK_WIDGET(totem_get_main_window(lrc_totem)));
//	gtk_container_set_resize_mode(GTK_CONTAINER(win), GTK_RESIZE_PARENT);
//	gtk_container_set_resize_mode(GTK_CONTAINER(wd), GTK_RESIZE_QUEUE);
	gtk_container_add(GTK_CONTAINER(win),wd);
	gtk_window_set_gravity(GTK_WINDOW(win),GDK_GRAVITY_NORTH_EAST);
	gtk_window_set_position(GTK_WINDOW(win),GTK_WIN_POS_CENTER);
	g_signal_connect(win,"delete-event",G_CALLBACK(on_lrcshow_win),NULL);

	return GTK_WINDOW(win);
}
/*
gchar *lrc_get_lyric_file(int flag)
{
  static int count = -1;
  static gchar lrc_name[257]={0};
  static char *lrc_paths[15]={NULL};
  count+=flag;
  if(count<-1||count>15||(count>0&&lrc_paths[count]==NULL)){
     lmp_debug("count = %d",count);
     count=-1;
     return NULL;
   }
  if(count==-1){
    int i=0;
    while(lrc_paths[i]){
      g_free(lrc_paths[i]);
      lrc_paths[i]=NULL;
      i++;
    }
    strcpy(lrc_name,basename(lyric_filename));
    lrc_paths[0] = g_strdup_printf("%s/lyrics/%s",getenv("HOME"),lrc_name);
    g_print("fuck %s\n",lrc_paths[0]);
    gchar *tmpstr = dirname(g_strdup(lrc_paths[0]));
    if(rmdir(tmpstr)==-1);
      fprintf(stderr,"rmdir():%s->%s\n",strerror(errno),tmpstr);

    if(access(tmpstr,F_OK)&&mkdir(tmpstr,S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH)==-1)
      fprintf(stderr,"mkdir():%s\n",strerror(errno));
    g_free(tmpstr);
    count ++;
  }
  return lrc_paths[count];
}



void lrc_config_save_load(gboolean flag)
{
	lmp_debug("%s",flag?"TRUE":"FALSE");
	gchar *config = g_strdup_printf("%s/.lrcshow",getenv("HOME"));
	FILE *fp = NULL;
	lrc_show = FALSE;
	if(flag){
		fp = fopen(config,"w");
		if(!fp){
			fprintf(stderr,"fopen():%s .\n",strerror(errno));
			return ;
		}
		fprintf(fp,"lrc_show=%d\n",lrc_show);
	}
	else{
		fp = fopen(config,"r");
		if(!fp){
			fprintf(stderr,"fopen():%s .\n",strerror(errno));
			return;
		}
		lrc_show = lrc_get_value("lrc_show",fp);
	}
	fclose(fp);
}
*/
